#include "PrecompiledHeaders.h"
#include "ReplayController.h"

ReplayController::ReplayController(std::string filename)
{
    load(filename);
    start();
}

ReplayController::ReplayController(std::vector<GravityState> gs)
{
    gravityStates = gs;
    start();
}

ReplayController::~ReplayController()
{
}

bool ReplayController::registerBall(Ball *b)
{
    ball = b;
    start();
    return true;
}

void ReplayController::unregisterBall()
{
    ball = NULL;
}

/*
 * Start a playback
 */
void ReplayController::start()
{
    playbackIndex = 0;
}

bool ReplayController::ogreNewtNeedsUpdate(Ogre::Real time_since_last)
{
    if(playbackIndex >= (int)(gravityStates.size()))
    {
        ball->getPlayer()->finished();
        return true;
    }
    return time_since_last >= gravityStates[playbackIndex].time;
}

float ReplayController::getOgreNewtUpdateTime()
{
    return gravityStates[playbackIndex].time;
}

/*
 * This method is called to set the position of the playback array, 
 * in order to access the correct x and y values. It gets called every time
 * a frame is rendered in the game
 */
void ReplayController::updateBall(Ogre::Real elapsedFrameTime)
{
    if(playbackIndex < (int)(gravityStates.size()))
    {
        ball->setGravity(gravityStates[playbackIndex].gravity);
        playbackIndex++;
    }
    else
        ball->setGravity(Ogre::Vector3::NEGATIVE_UNIT_Y);
}

/*
 * Load a replay from a file
 */
void ReplayController::load(std::string filename)
{
    GravityState gravityState;
    gravityStates.clear();
    file.open(filename.c_str(), std::ios::in | std::ios::binary);
    int i = 0;
    while(!file.eof()) {
        file.read((char *)&gravityState, sizeof(gravityState));
        gravityStates.push_back(gravityState);
        i++;
    }
    file.close();
}

void ReplayController::reset()
{
    playbackIndex = 0;
}
